package com.leizhi.demo.monitor.service.impl;

import com.leizhi.demo.monitor.achieve.PushStreamService;
import com.leizhi.demo.monitor.achieve.SipService;
import com.leizhi.demo.monitor.cache.DeviceCache;
import com.leizhi.demo.monitor.pojo.*;
import com.leizhi.demo.monitor.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MonitorServiceImpl implements MonitorService {

    @Autowired
    private DeviceCache deviceCache;
    @Autowired
    private SipService sipService;
    @Autowired
    private PushStreamService pushStreamService;


    @Override
    public MediaData play(String deviceId) {
        PushStreamInfo pushStream = pushStreamService.getPushStream(deviceId);
        if (pushStream == null || !pushStream.getIsPushStream()) {
            pushStream = pushStreamService.sendInvite(deviceId);
        }

        return new MediaData(pushStream.getPullStreamAddress(), pushStream.getCallId());
    }

    @Override
    public void bye(String deviceId) {
        PushStreamInfo stream = pushStreamService.getPushStream(deviceId);
        if (stream != null) {
            pushStreamService.stop(deviceId);
            sipService.sendBye(stream);
        }
    }

    @Override
    public void onCloud(String deviceId) {
        Device device = deviceCache.select(deviceId);
        if (device == null) {
            throw new RuntimeException("设备未注册");
        }

        // 更新缓存信息
        if (!device.getIsCloud()) {
            device.setIsCloud(true);
            deviceCache.add(deviceId, device);
        }

        PushStreamInfo pushStream = pushStreamService.getPushStream(deviceId);
        if (pushStream != null && pushStream.getIsPushStream()) {
            pushStreamService.getProcess(pushStream.getSsrc()).setCloud(true);
            return;
        }
        pushStreamService.sendInvite(deviceId);
    }

    @Override
    public void offCloud(String deviceId) {
        Device device = deviceCache.select(deviceId);
        if (device == null) {
            throw new RuntimeException("设备未注册");
        }

        // 更新缓存信息
        if (!device.getIsCloud()) {
            device.setIsCloud(false);
            deviceCache.add(deviceId, device);
        }

        PushStreamInfo channel = pushStreamService.getPushStream(deviceId);
        if (channel != null && channel.getIsPushStream()) {
            pushStreamService.getProcess(channel.getSsrc()).setCloud(false);
        }
    }

}
